package com.hjj.controller;

import com.hjj.beans.Stu;
import com.hjj.exception.MyRoundException;
import com.hjj.services.StuServices;
import com.hjj.services.StuServicesImp;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;

import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;

public class StuController implements Initializable {
    // 关联业务层
    StuServices stuServices = new StuServicesImp();

    @FXML
    private Button btnAdd;

    @FXML
    private Button btnEdit;

    @FXML
    private Button btnDel;

    @FXML
    private Button btnGetAll;

    @FXML
    private Button btnCallRoll;


    @FXML
    private TextField text;

    @FXML
    private TableView<Stu> table;

    @FXML
    private TableColumn<Stu, Integer> tId;

    @FXML
    private TableColumn<Stu, String> tName;

    @FXML
    private TableColumn<Stu, Integer> tAge;

    @FXML
    private TableColumn<Stu, String> tSex;

    @FXML
    private TableColumn<Stu, Float> tScore;

    @FXML
    void add(ActionEvent event) {
        URL resource = StuController.class.getResource("/view/StuAdd.fxml");
        Node node = null;
        try {
            node = FXMLLoader.load(resource);
        } catch (IOException e) {
            error("加载资源失败");
            return;
        }

        TextField tId = (TextField) node.lookup("#tId");
        TextField tName = (TextField) node.lookup("#tName");
        TextField tAge = (TextField) node.lookup("#tAge");
        RadioButton rSexM = (RadioButton) node.lookup("#rSexM");
        TextField tScore = (TextField) node.lookup("#tScore");

        tId.setEditable(false);
        tId.setText("ID由系统自动生成");

        DialogPane dialogPane = new DialogPane();

        dialogPane.setContent(node);

        dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        Dialog dialog = new Dialog();

        dialog.setDialogPane(dialogPane);

        dialog.setTitle("添加学生信息");

        Optional<ButtonType> buttonType = dialog.showAndWait();

        if (buttonType.get() == ButtonType.OK){
            Stu stu = new Stu();

            stu.setName(tName.getText());
            try {
                stu.setAge(Integer.parseInt(tAge.getText()));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                error("年龄只能输入整数");
                return;
            }
            if (rSexM.isSelected()){
                stu.setSex("男");
            }else {
                stu.setSex("女");
            }
            try {
                stu.setScore(Float.parseFloat(tScore.getText()));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                error("成绩只能是数字");
                return;
            }

            boolean add = false;
            try {
                add = stuServices.add(stu);
            } catch (SQLException e) {
                e.printStackTrace();
                error("添加SQL语句错误");
                return;
            } catch (MyRoundException e) {
                e.printStackTrace();
                error(e.getMessage());
                return;
            }

            if (!add){
                information("添加数据失败");
                return;
            }

            flushData();


        }

    }

    @FXML
    void callRoll(ActionEvent event) {
        int num = 0;
        try {
            num = Integer.parseInt(text.getText());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            error("请输入整数点名");
            return;
        }

        String list = null;
        try {
            list = stuServices.callRoll(num);
        } catch (SQLException e) {
            e.printStackTrace();
            error("查询所有的SQL语句错误");
            return;
        } catch (MyRoundException e) {
            e.printStackTrace();
            error(e.getMessage());
            return;
        }

        information(list);
    }

    @FXML
    void del(ActionEvent event) {
        Stu selectedItem = table.getSelectionModel().getSelectedItem();
        if (selectedItem == null){
            information("没有选中任何一行，无法进行删除");
            return;
        }

        Alert alert = new Alert(Alert.AlertType.INFORMATION, "是否确定要删除该学生数据", ButtonType.OK, ButtonType.CANCEL);
        Optional<ButtonType> buttonType = alert.showAndWait();

        if (buttonType.get() == ButtonType.OK){
            boolean del = false;
            try {
                del = stuServices.del(selectedItem.getId());
            } catch (SQLException e) {
                e.printStackTrace();
                error("删除SQL语句错误");
                return;
            }

            if (!del){
                information("删除失败");
                return;
            }

            flushData();
        }
    }

    @FXML
    void edit(ActionEvent event) {
        URL resource = StuController.class.getResource("/view/StuAdd.fxml");
        Node node = null;
        try {
            node = FXMLLoader.load(resource);
        } catch (IOException e) {
            error("加载资源失败");
            return;
        }

        // 获取表格中选中的学生数据
        Stu selectedItem = table.getSelectionModel().getSelectedItem();
        if (selectedItem == null){
            information("没有选中任何一行数据，无法进行修改");
            return;
        }

        TextField tId = (TextField) node.lookup("#tId");
        TextField tName = (TextField) node.lookup("#tName");
        TextField tAge = (TextField) node.lookup("#tAge");
        RadioButton rSexM = (RadioButton) node.lookup("#rSexM");
        RadioButton rSexW = (RadioButton) node.lookup("#rSexW");
        TextField tScore = (TextField) node.lookup("#tScore");

        tId.setEditable(false);
        tId.setText(String.valueOf(selectedItem.getId()));
        tName.setText(selectedItem.getName());
        tAge.setText(String.valueOf(selectedItem.getAge()));
        if ("男".equals(selectedItem.getSex())){
            rSexM.setSelected(true);
        }else {
            rSexW.setSelected(true);
        }
        tScore.setText(String.valueOf(selectedItem.getScore()));


        DialogPane dialogPane = new DialogPane();

        dialogPane.setContent(node);

        dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        Dialog dialog = new Dialog();

        dialog.setDialogPane(dialogPane);

        dialog.setTitle("修改学生信息");

        Optional<ButtonType> buttonType = dialog.showAndWait();

        if (buttonType.get() == ButtonType.OK){


            Stu stu = new Stu();

            stu.setId(Integer.parseInt(tId.getText()));
            stu.setName(tName.getText());
            try {
                stu.setAge(Integer.parseInt(tAge.getText()));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                error("年龄只能输入整数");
                return;
            }
            if (rSexM.isSelected()){
                stu.setSex("男");
            }else {
                stu.setSex("女");
            }
            try {
                stu.setScore(Float.parseFloat(tScore.getText()));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                error("成绩只能是数字");
                return;
            }

            boolean edit = false;
            try {
                edit = stuServices.edit(stu);
            } catch (SQLException e) {
                e.printStackTrace();
                error("修改SQL语句错误");
                return;
            } catch (MyRoundException e) {
                e.printStackTrace();
                error(e.getMessage());
                return;
            }

            if (!edit){
                information("修改数据失败");
                return;
            }

            flushData();


        }
    }

    @FXML
    void getAll(ActionEvent event) {
        flushData();
    }

    public void flushData() {
        ArrayList<Stu> all = null;
        try {
            all = stuServices.getAll();
        } catch (SQLException e) {
            e.printStackTrace();
            error("查询所有的SQL语句错误");
            return;
        }

        table.getItems().clear();

        ObservableList<Stu> stus = FXCollections.observableArrayList(all);

        // 绑定每一列的数据
        tId.setCellValueFactory(new PropertyValueFactory<Stu, Integer>("id"));
        tName.setCellValueFactory(new PropertyValueFactory<Stu, String>("name"));
        tAge.setCellValueFactory(new PropertyValueFactory<Stu, Integer>("age"));
        tSex.setCellValueFactory(new PropertyValueFactory<Stu, String>("sex"));
        tScore.setCellValueFactory(new PropertyValueFactory<Stu, Float>("score"));

        table.setItems(stus);
    }

    public void information(String contentText){
        Alert alert = new Alert(Alert.AlertType.INFORMATION, contentText, ButtonType.OK);
        alert.show();
    }

    public void error(String contentText){
        Alert alert = new Alert(Alert.AlertType.ERROR, contentText, ButtonType.OK);
        alert.show();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        flushData();
    }
}